#import "ViewController.h"
#import <WebRTC/WebRTC.h>
#import <SocketRocket/SocketRocket.h>
#import <Masonry/Masonry.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController () <SRWebSocketDelegate, RTCPeerConnectionDelegate>
@property(nonatomic, strong) RTCPeerConnectionFactory *factory;
@property(nonatomic, strong) SRWebSocket *webSocket;
@property(nonatomic, strong) RTCPeerConnection *peerConnection;
@property(nonatomic, strong) UIButton *openWebSocketButton;
@property(nonatomic, strong) UIButton *closeWebSocketButton;
@property(nonatomic, strong) UILabel *webSocketLabel;
@property(nonatomic, strong) UIButton *offerButton;
@property(nonatomic, strong) UIButton *audioCallButton;
@property(nonatomic, strong) UITextField *textInputField;
@property(nonatomic, strong) UIButton *sendTextMessageButton;


@property (nonatomic, strong) UIView *fullScreenView;
@property (nonatomic, strong) UIButton *showFullScreenViewButton;
@property (nonatomic, strong) UIButton *closeFullScreenViewButton;


@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;

@property (nonatomic, strong) UIView *localVideoView; // 用于显示本地视频的视图
@property (nonatomic, strong) UIView *remoteVideoView; // 用于显示远程视频的视图

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;

    // 创建并设置打开WebSocket的按钮
    self.openWebSocketButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.openWebSocketButton setTitle:@"打开WebSocket" forState:UIControlStateNormal];
    [self.openWebSocketButton addTarget:self action:@selector(openWebSocket) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.openWebSocketButton];
    
    [self.openWebSocketButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(100);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(20);
        make.width.mas_equalTo(150);
    }];

    // 创建label显示是否连接成功
    self.webSocketLabel = [UILabel new];
    [self.view addSubview:self.webSocketLabel];
    [self.webSocketLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.openWebSocketButton.mas_bottom).offset(10);
        make.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(20);
    }];
    self.webSocketLabel.textAlignment = NSTextAlignmentCenter;
    self.webSocketLabel.font = [UIFont systemFontOfSize:12];
    self.webSocketLabel.textColor = [UIColor redColor];
    self.webSocketLabel.text = @"webSocket信令未链接";

    // 创建并设置关闭WebSocket的按钮
    self.closeWebSocketButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.closeWebSocketButton setTitle:@"关闭WebSocket" forState:UIControlStateNormal];
    [self.closeWebSocketButton addTarget:self action:@selector(closeWebSocket) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.closeWebSocketButton];
    
    [self.closeWebSocketButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.webSocketLabel.mas_bottom).offset(10);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(20);
        make.width.mas_equalTo(150);
    }];

    // 创建Offer按钮
    self.offerButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.offerButton setTitle:@"语音通讯" forState:UIControlStateNormal];
    [self.offerButton addTarget:self action:@selector(createOffer) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.offerButton];
    [self.offerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.closeWebSocketButton.mas_bottom).offset(10);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(20);
        make.width.mas_equalTo(150);
    }];
    // 初始化PeerConnectionFactory
    self.factory = [[RTCPeerConnectionFactory alloc] init];
    
    
    // 创建并设置文本输入框
        self.textInputField = [[UITextField alloc] init];
        self.textInputField.borderStyle = UITextBorderStyleRoundedRect;
        self.textInputField.placeholder = @"输入消息...";
        [self.view addSubview:self.textInputField];

        [self.textInputField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.offerButton.mas_bottom).offset(20);
            make.centerX.equalTo(self.view);
            make.height.mas_equalTo(30);
            make.width.mas_equalTo(200);
        }];

        // 创建并设置发送文本消息的按钮
        self.sendTextMessageButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [self.sendTextMessageButton setTitle:@"发送文本消息" forState:UIControlStateNormal];
        [self.sendTextMessageButton addTarget:self action:@selector(sendTextMessageButtonTapped) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.sendTextMessageButton];

        [self.sendTextMessageButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.textInputField.mas_bottom).offset(10);
            make.centerX.equalTo(self.view);
            make.height.mas_equalTo(20);
            make.width.mas_equalTo(150);
        }];
    
    
    
    // 创建并设置显示全屏视图的按钮
        self.showFullScreenViewButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [self.showFullScreenViewButton setTitle:@"显示全屏视图" forState:UIControlStateNormal];
        [self.showFullScreenViewButton addTarget:self action:@selector(showFullScreenView) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.showFullScreenViewButton];

        [self.showFullScreenViewButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.bottom.equalTo(self.view).offset(-50); // 或者其他适合您布局的位置
            make.height.mas_equalTo(30);
            make.width.mas_equalTo(150);
        }];
}
- (void)showFullScreenView {
    // 创建全屏视图
    self.fullScreenView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.fullScreenView.backgroundColor = [UIColor blackColor]; // 或其他您喜欢的颜色
    [self.view addSubview:self.fullScreenView];

    // 创建并设置关闭全屏视图的按钮
    self.closeFullScreenViewButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.closeFullScreenViewButton setTitle:@"关闭视图" forState:UIControlStateNormal];
    [self.closeFullScreenViewButton addTarget:self action:@selector(closeFullScreenView) forControlEvents:UIControlEventTouchUpInside];
    [self.fullScreenView addSubview:self.closeFullScreenViewButton];

    [self.closeFullScreenViewButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.fullScreenView).offset(20);
        make.bottom.equalTo(self.fullScreenView).offset(-20);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(100);
    }];

    // 创建用于显示本地和远程视频的视图
    self.localVideoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.fullScreenView.bounds.size.width, self.fullScreenView.bounds.size.height / 2)];
    [self.fullScreenView addSubview:self.localVideoView];

    self.remoteVideoView = [[UIView alloc] initWithFrame:CGRectMake(0, self.fullScreenView.bounds.size.height / 2, self.fullScreenView.bounds.size.width, self.fullScreenView.bounds.size.height / 2)];
    [self.fullScreenView addSubview:self.remoteVideoView];

    // 确保 peerConnection 已创建并准备好进行视频通信
    if (!self.peerConnection) {
        [self createPeerConnection];
    }

    // 创建 offer 或处理远程 offer（根据您的逻辑）
    [self createOffer];

    // 配置 AVCaptureSession
    [self setupCaptureSession];
}

- (void)setupCaptureSession {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        // 创建 AVCaptureSession
        self.captureSession = [[AVCaptureSession alloc] init];

        // 获取前置摄像头
        AVCaptureDevice *frontCamera = nil;
        NSArray *cameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
        for (AVCaptureDevice *device in cameras) {
            if (device.position == AVCaptureDevicePositionFront) {
                frontCamera = device;
                break;
            }
        }

        if (!frontCamera) {
            NSLog(@"前置摄像头不可用");
            return;
        }

        NSError *error = nil;
        AVCaptureDeviceInput *frontCameraInput = [AVCaptureDeviceInput deviceInputWithDevice:frontCamera error:&error];
        if (error) {
            NSLog(@"Error getting front camera input device: %@", error.localizedDescription);
            return;
        }

        if ([self.captureSession canAddInput:frontCameraInput]) {
            [self.captureSession addInput:frontCameraInput];
        }

        // 启动视频捕获会话
        [self.captureSession startRunning];

        dispatch_async(dispatch_get_main_queue(), ^{
            // 创建并添加本地视频预览层到 localVideoView
            self.videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
            self.videoPreviewLayer.frame = self.localVideoView.bounds;
            self.videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
            [self.localVideoView.layer addSublayer:self.videoPreviewLayer];
        });
    });
}




- (void)closeFullScreenView {
    [self.captureSession stopRunning];
    self.captureSession = nil;
    [self.videoPreviewLayer removeFromSuperlayer];
    self.videoPreviewLayer = nil;

    [self.fullScreenView removeFromSuperview];
}

- (void)openWebSocket {
    // 初始化WebSocket
    [self setupWebSocket];
}

- (void)setupWebSocket {
    NSURL *url = [NSURL URLWithString:@"ws://192.168.3.14:8080"]; // 信令服务器
    self.webSocket = [[SRWebSocket alloc] initWithURL:url];
    self.webSocket.delegate = self;
    [self.webSocket open];
}

- (void)closeWebSocket {
    if (self.webSocket) {
        [self.webSocket close];
        self.webSocket = nil;
        NSLog(@"WebSocket已关闭");
    }
}

- (void)createPeerConnection {
    RTCConfiguration *config = [[RTCConfiguration alloc] init];
    // 配置 STUN 和 TURN 服务器
    NSArray *iceServers = @[
        [[RTCIceServer alloc] initWithURLStrings:@[@"stun:stun.l.google.com:19302"]] // 中继服务器
    ];
    config.iceServers = iceServers;

    RTCMediaConstraints *constraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:nil optionalConstraints:nil];
    self.peerConnection = [self.factory peerConnectionWithConfiguration:config constraints:constraints delegate:self];
    
    // 创建并添加音频轨道
    [self addAudioTrack];
    
    // 添加视频轨道
       [self addVideoTrack];
}

- (void)addAudioTrack {
    RTCAudioTrack *audioTrack = [self.factory audioTrackWithTrackId:@"audio0"];
    [self.peerConnection addTrack:audioTrack streamIds:@[@"stream0"]];
}

- (void)createOffer {
    [self.peerConnection offerForConstraints:[self defaultOfferConstraints] completionHandler:^(RTCSessionDescription * _Nullable sdp, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Error creating offer: %@", error);
            return;
        }
        [self.peerConnection setLocalDescription:sdp completionHandler:^(NSError * _Nullable error) {
            if (error) {
                NSLog(@"Error setting local description: %@", error);
                return;
            }
            // 发送offer到WebSocket服务器
            [self sendOffer:sdp];
        }];
    }];
}

- (void)sendOffer:(RTCSessionDescription *)offer {
    NSDictionary *offerDict = @{@"type": @"offer", @"sdp": offer.sdp};
    NSData *offerData = [NSJSONSerialization dataWithJSONObject:offerDict options:0 error:nil];
    NSString *offerString = [[NSString alloc] initWithData:offerData encoding:NSUTF8StringEncoding];
    [self.webSocket send:offerString];
    NSLog(@"Offer已发送: %@", offerString);
}

- (void)setRemoteAnswer:(RTCSessionDescription *)answer {
    [self.peerConnection setRemoteDescription:answer completionHandler:^(NSError * _Nullable error) {
        if (error) {
            NSLog(@"设置远程Answer时出错: %@", error);
            return;
        }
        NSLog(@"成功接收并设置远程Answer");
        // 连接建立完成，可以添加其他逻辑
    }];
}

- (RTCMediaConstraints *)defaultOfferConstraints {
    NSDictionary *mandatoryConstraints = @{@"OfferToReceiveAudio": @"true", @"OfferToReceiveVideo": @"true"};
    RTCMediaConstraints *constraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:mandatoryConstraints optionalConstraints:nil];
    return constraints;
}

#pragma mark - SRWebSocketDelegate Methods

- (void)webSocketDidOpen:(SRWebSocket *)webSocket {
    NSLog(@"WebSocket连接成功");
    self.webSocketLabel.text = @"WebSocket连接成功";
    // 创建PeerConnection
    [self createPeerConnection];
}

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
    NSLog(@"WebSocket连接失败：%@", error);
    self.webSocketLabel.text = @"WebSocket连接失败";
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
    NSString *messageString = [self stringFromWebSocketMessage:message];
    NSDictionary *messageDict = [NSJSONSerialization JSONObjectWithData:[messageString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
    if ([messageDict[@"type"] isEqualToString:@"text"]) {
           // 接收到文本消息时的处理
           NSString *receivedMessage = messageDict[@"content"];
           [self showAlertWithMessage:receivedMessage];
       }else if ([messageDict[@"type"] isEqualToString:@"offer"]) {
        // 如果是Offer消息，处理Offer
        RTCSessionDescription *offer = [[RTCSessionDescription alloc] initWithType:RTCSdpTypeOffer sdp:messageDict[@"sdp"]];
        [self handleReceivedOffer:offer];
    } else if ([messageDict[@"type"] isEqualToString:@"answer"]) {
        // 如果是Answer消息，设置远程Answer
        RTCSessionDescription *answer = [[RTCSessionDescription alloc] initWithType:RTCSdpTypeAnswer sdp:messageDict[@"sdp"]];
        [self setRemoteAnswer:answer];
    }else if ([messageDict[@"type"] isEqualToString:@"candidate"]) {
           RTCIceCandidate *candidate = [[RTCIceCandidate alloc] initWithSdp:messageDict[@"candidate"]
                                                                    sdpMLineIndex:[messageDict[@"sdpMLineIndex"] intValue]
                                                                        sdpMid:messageDict[@"sdpMid"]];
           [self.peerConnection addIceCandidate:candidate];
       }
}

- (void)handleReceivedMessage:(NSString *)messageString {
    NSDictionary *messageDict = [NSJSONSerialization JSONObjectWithData:[messageString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
    if ([messageDict[@"type"] isEqualToString:@"answer"]) {
        RTCSessionDescription *answer = [[RTCSessionDescription alloc] initWithType:RTCSdpTypeAnswer sdp:messageDict[@"sdp"]];
        [self setRemoteAnswer:answer];
    }
}


- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
    NSLog(@"WebSocket连接关闭，原因：%@", reason);
    self.webSocketLabel.text = @"WebSocket连接关闭";
}

#pragma mark - RTCPeerConnectionDelegate Methods

- (void)peerConnectionShouldNegotiate:(RTCPeerConnection *)peerConnection {
    // 协商需要时的处理
    NSLog(@"协商需要时的处理");
}

- (void)peerConnection:(RTCPeerConnection *)peerConnection didChangeIceConnectionState:(RTCIceConnectionState)newState {
    // ICE连接状态变化时的处理
    NSLog(@"ICE连接状态变化时的处理");
}

- (void)peerConnection:(RTCPeerConnection *)peerConnection didChangeIceGatheringState:(RTCIceGatheringState)newState {
    // ICE收集状态变化时的处理
    NSLog(@"ICE收集状态变化时的处理");
}

- (void)peerConnection:(RTCPeerConnection *)peerConnection didGenerateIceCandidate:(RTCIceCandidate *)candidate {
    // 处理新生成的ICE候选者
    NSLog(@"处理新生成的ICE候选者");
    NSDictionary *candidateDict = @{@"type": @"candidate",
                                       @"sdpMid": candidate.sdpMid,
                                       @"sdpMLineIndex": @(candidate.sdpMLineIndex),
                                       @"candidate": candidate.sdp};
       NSData *candidateData = [NSJSONSerialization dataWithJSONObject:candidateDict options:0 error:nil];
       NSString *candidateString = [[NSString alloc] initWithData:candidateData encoding:NSUTF8StringEncoding];
       [self.webSocket send:candidateString];
       NSLog(@"ICE候选已发送: %@", candidateString);
}

- (void)peerConnection:(RTCPeerConnection *)peerConnection didOpenDataChannel:(RTCDataChannel *)dataChannel {
    // 数据通道打开时的处理
    NSLog(@"数据通道打开时的处理");
}
- (void)peerConnection:(RTCPeerConnection *)peerConnection didChangeSignalingState:(RTCSignalingState)stateChanged {
    switch (stateChanged) {
        case RTCSignalingStateStable:
            NSLog(@"Signaling state: Stable");
            break;
        case RTCSignalingStateHaveLocalOffer:
            NSLog(@"Signaling state: Have Local Offer");
            break;
        case RTCSignalingStateHaveLocalPrAnswer:
            NSLog(@"Signaling state: Have Local PrAnswer");
            break;
        case RTCSignalingStateHaveRemoteOffer:
            NSLog(@"Signaling state: Have Remote Offer");
            break;
        case RTCSignalingStateHaveRemotePrAnswer:
            NSLog(@"Signaling state: Have Remote PrAnswer");
            break;
        case RTCSignalingStateClosed:
            NSLog(@"Signaling state: Closed");
            break;
    }
}



- (void)handleReceivedOffer:(RTCSessionDescription *)offer {
    [self.peerConnection setRemoteDescription:offer completionHandler:^(NSError * _Nullable error) {
        if (error) {
            NSLog(@"Error setting remote offer: %@", error);
            return;
        }
        [self createAndSendAnswer];
    }];
}

- (void)createAndSendAnswer {
    [self.peerConnection answerForConstraints:[self defaultAnswerConstraints] completionHandler:^(RTCSessionDescription * _Nullable sdp, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Error creating answer: %@", error);
            return;
        }
        [self.peerConnection setLocalDescription:sdp completionHandler:^(NSError * _Nullable error) {
            if (error) {
                NSLog(@"Error setting local description: %@", error);
                return;
            }
            // 发送Answer
            [self sendAnswer:sdp];
        }];
    }];
}

- (void)sendAnswer:(RTCSessionDescription *)answer {
    NSDictionary *answerDict = @{@"type": @"answer", @"sdp": answer.sdp};
    NSData *answerData = [NSJSONSerialization dataWithJSONObject:answerDict options:0 error:nil];
    NSString *answerString = [[NSString alloc] initWithData:answerData encoding:NSUTF8StringEncoding];
    [self.webSocket send:answerString];
}

// 将WebSocket消息转换为字符串
- (NSString *)stringFromWebSocketMessage:(id)message {
    if ([message isKindOfClass:[NSData class]]) {
        return [[NSString alloc] initWithData:message encoding:NSUTF8StringEncoding];
    } else if ([message isKindOfClass:[NSString class]]) {
        return message;
    }
    return nil;
}

// 默认的Answer约束
- (RTCMediaConstraints *)defaultAnswerConstraints {
    NSDictionary *mandatoryConstraints = @{@"OfferToReceiveAudio": @"true", @"OfferToReceiveVideo": @"false"};
    RTCMediaConstraints *constraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:mandatoryConstraints optionalConstraints:nil];
    return constraints;
}

- (void)peerConnection:(RTCPeerConnection *)peerConnection didAddStream:(RTCMediaStream *)stream {
    NSLog(@"Stream added: %@", stream);

    // 处理音频轨道
    if (stream.audioTracks.count > 0) {
        RTCAudioTrack *audioTrack = stream.audioTracks[0];
        audioTrack.isEnabled = YES;
    }

    // 处理视频轨道
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"处理视频轨道%lu",(unsigned long)stream.videoTracks.count);
        if (stream.videoTracks.count > 0) {
            RTCVideoTrack *remoteVideoTrack = stream.videoTracks[0];


            // 创建并设置远程视频视图
            RTCEAGLVideoView *remoteVideoView1 = [[RTCEAGLVideoView alloc] initWithFrame:self.remoteVideoView.bounds];
            [self.remoteVideoView addSubview:remoteVideoView1];
            [remoteVideoTrack addRenderer:remoteVideoView1];
        }
    });
}





#pragma mark - 发送和接收文本消息

- (void)sendTextMessage:(NSString *)message {
    NSDictionary *messageDict = @{@"type": @"text", @"content": message};
    NSData *messageData = [NSJSONSerialization dataWithJSONObject:messageDict options:0 error:nil];
    NSString *messageString = [[NSString alloc] initWithData:messageData encoding:NSUTF8StringEncoding];
    [self.webSocket send:messageString];
}

#pragma mark - 显示弹窗

- (void)showAlertWithMessage:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"接收到的消息" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)sendTextMessageButtonTapped {
    NSString *message = self.textInputField.text;
    if (message.length > 0) {
        [self sendTextMessage:message];
        self.textInputField.text = @""; // 清空文本框
    } else {
        NSLog(@"文本框为空，未发送消息");
    }
}


// 视频轨道
- (void)addVideoTrack {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];

    if ([self.captureSession canAddInput:input]) {
        [self.captureSession addInput:input];
    }

    AVCaptureVideoDataOutput *videoOutput = [[AVCaptureVideoDataOutput alloc] init];
    [videoOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];

    if ([self.captureSession canAddOutput:videoOutput]) {
        [self.captureSession addOutput:videoOutput];
    }

  
    
    RTCVideoSource *videoSource = [self.factory videoSource];
       RTCVideoTrack *videoTrack = [self.factory videoTrackWithSource:videoSource trackId:@"video0"];
       [self.peerConnection addTrack:videoTrack streamIds:@[@"stream0"]];
}

@end
